<?php
/**
 * h5页面(用户) 和 微信端(用户,店员） 的红包管理
 *
 * Author: lyun
 * Date: 2018/8/2
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\Wechat\Bonus;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Wechat\BonusIndexRequest;
use App\Models\Admin\StoreAdmin;
use App\Models\OpenWechat\WechatUser;
use App\Models\Panx\SkinRecordBonus;

class BonusController extends ApiController
{
    const ROUTE = [
        'index' => 'api.wechat.bonus'
    ];

    /**
     *  h5页面(用户) 和 微信端(用户,店员）领用红包的列表
     * @test
     *
     * @param BonusIndexRequest $request
     * @return array|\Illuminate\Http\Response
     * @throws \App\Exceptions\ApiAbstractException
     */
    public function index(BonusIndexRequest $request)
    {
        if ($request->has('store_admin_id')) {
            $data = $this->getStoreAdminBonuses($request->store_admin_id);
        } else {
            $data = $this->getWechatUserBonuses($request->openid);
        }

        return $this->response($data);
    }

    /**
     *  店员通过模板消息查看领用红包列表
     *
     * @param $store_admin_id
     * @return array|\Illuminate\Http\Response
     * @throws \App\Exceptions\ApiAbstractException
     */
    private function getStoreAdminBonuses($store_admin_id)
    {
        $store_admin = StoreAdmin::find($store_admin_id);
        $this->checkItemExist($store_admin, trans('admin.store_admin'));

        $bonuses = $store_admin->skinRecordBonuses()
            ->where('bonus_status', SkinRecordBonus::BONUS_STATUS_SUCCESS)
//            ->where('amount', '<>', SkinRecordBonus::BONUS_NO_GRANT_PAY_TYPE)
            ->latest()
            ->get();

        $headimgurl = optional($store_admin->wechatUser)->headimgurl;

        $total_amount = number_format($bonuses->sum('amount'), 2);

        return compact('bonuses', 'headimgurl', 'total_amount');
    }

    /**
     *  测肤用户 查看领用的红包列表
     *
     * @param $openid
     * @return array
     * @throws \App\Exceptions\ApiAbstractException
     */
    private function getWechatUserBonuses($openid)
    {
        /** @var WechatUser $wechat_user */
        $wechat_user = WechatUser::where('openid', $openid)
            ->first();
        $this->checkItemExist($wechat_user, trans('app.wechat_user_error'));

        $bonuses = $wechat_user->skinRecordBonuses()
            ->where('bonus_status', SkinRecordBonus::BONUS_STATUS_SUCCESS)
//            ->where('amount', '<>', SkinRecordBonus::BONUS_NO_GRANT_PAY_TYPE)
            ->latest()
            ->get();

        $headimgurl = $wechat_user->headimgurl;

        $total_amount = number_format($bonuses->sum('amount'), 2);

        return compact('bonuses', 'headimgurl', 'total_amount');
    }
}
